package cn.mallss.api.dao;


import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.data.jpa.domain.Specification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Component;

@Component
public class ExecSqlDao<T> {



    @Autowired
    private EntityManagerFactory emf;

    /**
     *
     * @param sql
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<T> getList(String sql, Class<T> clazz) {
        EntityManager em = emf.createEntityManager();
        Query query = em.createNativeQuery(sql, clazz);
        List<T> list = query.getResultList();
        em.close();
        return list;
    }

    public BigInteger total(String sql) {
        EntityManager em = emf.createEntityManager();
        Query query = em.createNativeQuery(sql);
        BigInteger list = (BigInteger) query.getSingleResult();
        em.close();
        return list;
    }


    public Integer update(String sql) {
        EntityManager entityManager = emf.createEntityManager();
        entityManager.getTransaction().begin();
        Query nativeQuery = entityManager.createNativeQuery(sql);
        int i = nativeQuery.executeUpdate();
        entityManager.getTransaction().commit();
        entityManager.close();
        return i;
    }

    /*public Page<T> search(String sql, Map<String,Object> parameter, Pageable pageable, Class<T> clazz){
        EntityManager em = emf.createEntityManager();
        Query query = em.createNativeQuery(sql, clazz);

        if (pageable.isPaged()) {
            query.setFirstResult((int) pageable.getOffset());
            query.setMaxResults(pageable.getPageSize());
        }


        return PageableExecutionUtils.getPage(query.getResultList(), pageable,
                () -> executeCountQuery(getCountQuery(spec, domainClass)));
	}*/
}
